package com.dailyyoga.common;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import cn.jpush.android.api.JPushInterface;

import com.dailyyoga.engine.R;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.ExceptionParser;
import com.google.analytics.tracking.android.ExceptionReporter;
import com.google.analytics.tracking.android.GAServiceManager;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.member.MemberManager;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.umeng.analytics.MobclickAgent;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class BasicActivity extends FragmentActivity implements
		IWXAPIEventHandler {

	private static HashMap<String, ArrayList<Activity>> mActivityBuffer;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (mActivityBuffer == null) {
			mActivityBuffer = new HashMap<String, ArrayList<Activity>>();
		}

		ArrayList<Activity> activities = mActivityBuffer.get(getClass()
				.getSimpleName());

		if (activities == null) {
			activities = new ArrayList<Activity>();
		}
		activities.add(this);

		mActivityBuffer.put(getClass().getSimpleName(), activities);

		mIsVisible = true;
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		initExceptionTracker();
		initAppdata();
	}

	private void initAppdata() {

		JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
		JPushInterface.init(this);
		MemberManager memberManager = MemberManager.getInstenc(this);
		memberManager.setContext(this);
		if (memberManager.getMyId() != null
				&& memberManager.getMyId().length() > 0) {
			memberManager.setMyId(memberManager.getMyId());
		}
	}

	static Tracker mTracker;

	void initExceptionTracker() {

		GoogleAnalytics myInstance = GoogleAnalytics.getInstance(this);
		mTracker = myInstance.getTracker(getString(R.string.ga_trackingId)
				.trim());

		ExceptionParser _exceptionParser = new ExceptionParser() {

			public String getDescription(String arg0, Throwable arg1) {
				// TODO Auto-generated method stub
				return getStackTrace(arg1);
			}

			private String getStackTrace(Throwable t) {
				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw, true);
				t.printStackTrace(pw);
				pw.flush();
				sw.flush();
				return sw.toString();
			}
		};
		ExceptionReporter myHandler = new ExceptionReporter(mTracker,
				GAServiceManager.getInstance(),
				Thread.getDefaultUncaughtExceptionHandler(), this);
		myHandler.setExceptionParser(_exceptionParser);
		Thread.setDefaultUncaughtExceptionHandler(myHandler);

		clearfiles();

	}

	public static Tracker getTrackerInstence(Context context) {

		return GoogleAnalytics.getInstance(context).getTracker(
				context.getString(R.string.ga_trackingId).trim());

	}

	protected void onStart() {
		EasyTracker.getInstance(this).activityStart(this);
		super.onStart();
	}

	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(getApplicationContext());

	}

	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(getApplicationContext());

	}

	protected void onStop() {

		EasyTracker.getInstance(this).activityStop(this);
		super.onStop();

	}

	public void homeFinish() {
		super.finish();
	}

	public boolean isAppOnForeground() {
		// Returns a list of application processes that are running on the
		// device

		ActivityManager activityManager = (ActivityManager) getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = getApplicationContext().getPackageName();

		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}

	public void onException(Exception exception) {
		Dialog dialog = new AlertDialog.Builder(this).setTitle("Error")
				.setMessage(exception.getMessage())
				.setNegativeButton(android.R.string.ok, null).create();
		dialog.show();
	}

	boolean mIsVisible;

	public boolean isVisible() {

		return mIsVisible;
	}

	protected void onDestroy() {

		ArrayList<Activity> activities = mActivityBuffer.get(getClass()
				.getSimpleName());

		if (activities != null) {
			activities.remove(this);

			if (activities.size() < 1) {
				mActivityBuffer.remove(getClass().getSimpleName());
			}

		}

		super.onDestroy();
	}

	public boolean isBuffered(String className) {
		return mActivityBuffer.get(className) != null;
	}

	public List<Activity> getBufferedActivity(String className) {
		return mActivityBuffer.get(className);
	}

	public void clearfiles() {

		Vector<File> files = new Vector<File>();

		File dailyyoga1 = new File( Environment.getExternalStorageDirectory().getPath() + ".dailyyogaCN/" );

		files.addElement(dailyyoga1);

		while (files.size() > 0) {
			File root = files.firstElement();
			if (root != null) {
				if (root.isDirectory()) {

					File[] list = root.listFiles();

					if (list != null) {
						for (File file : list) {

							if (file != null) {

								if (file.isDirectory()) {
									files.addElement(file);
								} else {
									file.delete();
								}
							}
						}
					}

				} else {

					System.out.println("文件==>" + root.getName());
				}

				root.delete();

				files.removeElement(root);
			}

		}

		dailyyoga1.delete();
	}

	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
	}

	public void onReq(BaseReq req) {
	}

	public void onResp(BaseResp resp) {

		int result = 0;

		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			result = R.string.errcode_success;
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
			result = R.string.errcode_cancel;
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
			result = R.string.errcode_deny;
			break;
		default:
			result = R.string.errcode_unknown;
			break;
		}
		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}

	int mIndex;
	int mTop;

	public int getIndex() {
		return mIndex;

	}

	public int getTop() {
		return mTop;
	}

	public void setBufferArgs(int index, int top) {
		mIndex = index;
		mTop = top;
	}

	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt("index", mIndex);
		outState.putInt("top", mTop);
		super.onSaveInstanceState(outState);

	}
}
